package com.example.java_gobang2.api;

import com.example.java_gobang2.mapper.UserMapper;
import com.example.java_gobang2.model.User;
import com.example.java_gobang2.model.UserRank;
import com.example.java_gobang2.service.RedisService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;;

    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return "账号或密码不能为空";
        }
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            return "账号错误";
        }
        if (!password.equals(user.getPassword())) {
            return "密码错误";
        }
        HttpSession session = request.getSession();
        session.setAttribute("user",user);

        return "登入成功";
    }

    @RequestMapping("/rank")
    public List<UserRank> getRank() {
        List<UserRank> userRanks = redisService.getCacheListByRange("userRank", 0, -1, UserRank.class);
        if (userRanks == null) {
            userRanks = new ArrayList<>();
            List<User> userList = userMapper.selectUserRank();
            int i = 1;
            for (User user : userList) {
                UserRank userRank = new UserRank();
                userRank.setUsername(user.getUsername());
                userRank.setScore(user.getScore());
                userRank.setRank(i++);
                userRanks.add(userRank);
            }
            redisService.setCacheObject("userRank",userRanks);
        }
        return userRanks;
    }

    @RequestMapping("/register")
    public String register(String username,String password) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return "账号或密码不能为空";
        }
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            User user1 = new User();
            user1.setUsername(username);
            user1.setPassword(password);
            userMapper.insertUser(user1);
            return "注册成功";
        }else {
            return "账号已存在";
        }
    }

    @RequestMapping("/userInfo")
    public User getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        return user;
    }

}
